package logic

import (
	"cartRpc/cache"
	"context"
	"fmt"
	"strconv"

	"cartRpc/cart"
	"cartRpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartListLogic {
	return &CartListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartListLogic) CartList(in *cart.CartListRequest) (*cart.CartListResponse, error) {
	// todo: add your logic here and delete this line
	key := fmt.Sprintf("cart_%d_*", in.UserId)
	keys := cache.Rdb.Keys(context.Background(), key).Val()

	if len(keys) == 0 {
		return &cart.CartListResponse{}, nil
	}

	var cartsList []*cart.CartItem
	for _, k := range keys {
		goodsMap, _ := cache.Rdb.HGetAll(context.Background(), k).Result()

		goodsId, _ := strconv.Atoi(goodsMap["goods_id"])
		num, _ := strconv.Atoi(goodsMap["goods_num"])
		price, _ := strconv.ParseFloat(goodsMap["goods_price"], 64)
		cartsList = append(cartsList, &cart.CartItem{
			UserId:     in.UserId,
			GoodsId:    int64(goodsId),
			GoodsName:  goodsMap["goods_name"],
			GoodsPrice: float32(price),
			Num:        int64(num),
		})
	}
	return &cart.CartListResponse{
		List: cartsList,
	}, nil
}
